<?php 
class controller{
	var $assign = array();
	var $args ='';
	var $_controller;
	
	public function run($url){
		$path = explode('/',$url);
//		print_r($path);
		
		$this->args = $this->explodePath($path);
		$this->loadController();
	}
	
	function loadController(){
		$controllerName = $this->args['controller'];
		$controllerFunction = $this->args['function'];
		$controllerTemplate = $this->args['template'];

		$this->controller = Import::loadClass('controller_'.$controllerName, 'controller/');
		$this->assign['arbo'] = $this->args['path'];
		
		//get id_collection
		if(!empty($this->args['id_collection']))
		$this->assign['id_collection'] = $this->args['id_collection'];
		
		if($_POST){
			if(method_exists(&$this->controller, $controllerFunction.'_post')){
				$zone['content'] = call_user_func(array(&$this->controller,$controllerFunction.'_post'), &$this->assign);
			}	
		}else{
			if(method_exists(&$this->controller, $controllerFunction)){
				$zone['content'] = call_user_func(array(&$this->controller,$controllerFunction), &$this->assign);
			}
		}
		
		if(isset($zone['content'])){
			include_once 'template/gabarit/'.$controllerTemplate.'.php';
		}else{
			include_once 'template/gabarit/404.tpl.php';
		}
		
		
		
	}
	
	function explodePath($path){
		$classTree = Import::loadClass('tree', 'library/');

		$directoryPage = $classTree->directory['page'];
		$directory_tmp = "";
		$webroot_url = '';
		$args = '';
		$request = '';
		
//		echo '<pre>';
//			print_r($directoryPage);
//		echo '</pre>';
		
//		echo'<pre>';
//		print_r($path);
//		echo '</pre>';
		
	    foreach($path as $path_key =>$path_value){
			if(!empty($path_value)){
//				echo '<li>'.$path_value;
				$request[] = $path_value;
				if(isset($directoryPage[$path_value])){  
//					echo '<li>1'.$path_value; 
					$directory_tmp = $directoryPage[$path_value];
					$webroot_url = $path_value;
						
				} elseif (isset($directory_tmp[$path_value])) {
//					echo '<li>2'.$path_value; 
						$directory_tmp = $directory_tmp[$path_value];
						$webroot_url .= '/'. $path_value;
				}else {
					$args[] = $path_value;
				}
				
			}
		
		}
		
		//default
		if (!is_array($directory_tmp)) {
			$directory_tmp = $directoryPage['index'];
		}
		
		//si pas de controller definie, recup l'index
		if(!isset($directory_tmp['controller'])){
			$directory_tmp = $directory_tmp['index'];
		}
		
		$directory_tmp['path'] = $path;
		
//		echo'<pre>';
//		print_r($directory_tmp);
//		echo '</pre>';
		
		return $directory_tmp;
	}
	
	function getSingleton (){
		return true;
	}
}
?>